package Action;

import java.util.List;
import java.util.UUID;
import java.io.*;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import javax.enterprise.deploy.spi.status.ProgressEvent;
import javax.enterprise.deploy.spi.status.ProgressListener;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.*;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.disk.*;
import org.apache.commons.fileupload.servlet.*;
import Dao.*;
import Entity.*;
import mapper.Noticemapper;
import mapper.Schedulemapper;

import com.jspsmart.upload.SmartUpload;

/**
 * Servlet implementation class addCourse
 */
@WebServlet("/addCourse")
public class addCourse extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
    // 锟较达拷锟侥硷拷锟芥储目录
    private static final String UPLOAD_DIRECTORY = "upload";
 
    // 锟较达拷锟斤拷锟斤拷
    private static final int MEMORY_THRESHOLD   = 1024 * 1024 * 3;  // 3MB
    private static final int MAX_FILE_SIZE      = 1024 * 1024 * 40; // 40MB
    private static final int MAX_REQUEST_SIZE   = 1024 * 1024 * 50; // 50MB
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public addCourse() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request,response);
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("gbk"); 
		response.setCharacterEncoding("gbk");
		response.setContentType("text/html; charset=gbk"); 
		HttpSession session=request.getSession();
		User user=(User) session.getAttribute("user");
		Date date=(Date) session.getAttribute("date_c");
		String roomid=(String) session.getAttribute("roomid");
		//System.out.println("");
		//System.out.println(roomid);
		int orderr=Integer.parseInt((String)session.getAttribute("orderr"));
		//System.out.println(orderr);
		java.sql.Date sdate=new java.sql.Date(date.getTime());
		//System.out.println(sdate);
		Room_ced rcdg=new Room_ced();
		rcdg.setDate(sdate);
		rcdg.setOrder(orderr);
		rcdg.setRoom_Id(roomid);
		coursedao csd=new coursedao();
		//rcdg.setRoom_Id(room_Id);
		Course cg=new Course();
		
		selectiondao scd=new selectiondao();
		
	        DiskFileItemFactory factory = new DiskFileItemFactory();
	        factory.setSizeThreshold(MEMORY_THRESHOLD);
	        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
	 
	        ServletFileUpload upload = new ServletFileUpload(factory);

	        upload.setFileSizeMax(MAX_FILE_SIZE);

	        upload.setSizeMax(MAX_REQUEST_SIZE);

	        upload.setHeaderEncoding("GBK"); 

	        String uploadPath = getServletContext().getRealPath("/") + File.separator + UPLOAD_DIRECTORY;

	        File uploadDir = new File(uploadPath);
	        if (!uploadDir.exists()) {
	            uploadDir.mkdir();
	        }
	 
	        SmartUpload smartUpload = new SmartUpload();
    		ServletConfig config = this.getServletConfig();
    		smartUpload.initialize(config, request, response);
    		String cid=null;
    		
		 try {
			 	smartUpload.upload();
			 	String t_name=smartUpload.getRequest().getParameter("t_name");
     			String c_name=smartUpload.getRequest().getParameter("c_name");
     			cg.setId(user.getUid());
     			cg.setCourse_Name(c_name);
     			System.out.println(t_name);
    		 	System.out.println(c_name);
    		 	com.jspsmart.upload.File smartFile = smartUpload.getFiles().getFile(0);
    			String name = smartFile.getFileName();
    			String str=session.getServletContext().getRealPath("/");
    			smartFile.saveAs(str+"/upload/"+name, SmartUpload.SAVE_AUTO);
    			request.setAttribute("message",
                        "锟轿程达拷锟斤拷锟缴癸拷!");
    			String filePath=str+"/upload/"+name;
    			System.out.println(filePath); 
    			File file = new File(filePath);
                InputStreamReader read = new InputStreamReader(
                new FileInputStream(file),"utf-8");
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt = null;
               cid=csd.CreatAll(cg, rcdg);
                
                while((lineTxt = bufferedReader.readLine()) != null){
						String [] spString = lineTxt.split("\\s+");
						int i=0;
						String sid = null;
						for(String ss : spString){
							if(i==0){
								sid=ss;
							}
							i++;
						    System.out.println(ss);
						}
						Selection sg=new Selection();
						sg.setCourse_Id(cid);
						sg.setId(sid);
						scd.CreatSelection(sg);
						Schedulemapper slm = new scheduledao();
						Room_ced rc = slm.getSchedule(cid);
						String context ="您已被安排进行一节新的实验课程！课程信息如下：\n课程标题："+rc.getCourse_Id()+"\n时间："+rc.getDate()+"\n（日期）第"+rc.getOrder()+"大节地点："+rc.getRoom_Id()+"\n机房详细信息请进入个人中心->我的课程查看！";
						Notice n =new Notice();
				        n.setContent(context);
				        n.setFrom_Id(t_name);
						n.setTo_Id(sid);
						Noticemapper nm = new noticedao();
					    boolean a =nm.sendMessage(n);}
                read.close();
                
	            
	        } catch (Exception ex) {
	            request.setAttribute("message",
	                    "锟斤拷锟斤拷锟斤拷息: " + ex.getMessage());
	        }
		 csd.updatestu(cid, 0);
		 request.getRequestDispatcher("queryCourses").forward(request,response);
		}
	
	}
